package com.zeng.ssm.util;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

/**
 * 描述信息
 *
 * @author zengwanlin
 * @date 2023-08-29T11:12
 */
public class TraceNoUtil {

    public static final String TRACE_NO = "traceNo";

    private static final int TRACE_NO_LEN = 10;

    private static final int CHILD_TRACE_NO_LEN = 5;

    private TraceNoUtil() {
    }

    public static void newTraceNo() {
        MDC.put(TRACE_NO, createTraceNo(TRACE_NO_LEN));
    }

    public static void newTraceNo(String parentTraceNo) {
        if (StringUtils.isBlank(parentTraceNo)) {
            newTraceNo();
        } else {
            MDC.remove(TRACE_NO);
            MDC.put(TRACE_NO, parentTraceNo + "-" + createTraceNo(CHILD_TRACE_NO_LEN));
        }
    }

    public static String getTraceNo() {
        return MDC.get(TRACE_NO);
    }

    public static void clearTraceNo() {
        MDC.remove(TRACE_NO);
    }

    private static String createTraceNo(int len) {
        return RandomStringUtils.randomAlphanumeric(len);
    }

}
